package com.skcc.ts.nsi;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.skcc.ts.nsi.service.SocketClientService;

public class MEIntro extends Activity {

	private Button btn_login;
	private Button btn_cancel;
	private String ptdDpcDate_1 = ""; // SMS 수신내용 중복처리 방지
	private String ptdDpcDate_2 = "_"; // SMS 수신내용 중복처리 방지
	private EditText login_addr;
	private EditText login_port;

	private EditText login_id;
	private EditText login_pw;
	private boolean selection;
	private String date;
	private String cost;
	private String distributor;
	private String addr;
	private String port;

	private int id = 11;// 기능분류(로그인)

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.intro);

		login_id = (EditText) findViewById(R.id.editText_login_id);
		login_pw = (EditText) findViewById(R.id.editText_login_pw);
		login_addr = (EditText) findViewById(R.id.editText_login_addr);
		login_port = (EditText) findViewById(R.id.editText_login_port);

		SharedPreferences prefs = getSharedPreferences("autoLogin", MODE_PRIVATE);

		login_id.setText(prefs.getString("p_UserId", ""));
		login_pw.setText(prefs.getString("p_UserPw", ""));
		login_addr.setText(prefs.getString("p_addr", ""));
		login_port.setText(prefs.getString("p_port", ""));

		if (checkSms() && !(ptdDpcDate_1.equals(ptdDpcDate_2))) { // SMS 수신체크, SMS 수신내용 중복처리 방지
			initButtons(true);
		} else {
			redoLogin(); // ID체크 & 패스워드 불일치 체크
			initButtons(false);// 버튼세팅(true :SMS 수신, false:정상로그인시도)
		}
	}

	private boolean checkSms() {// SMS 수신여부
		boolean doYN = false;
		Intent receiveI = getIntent();
		boolean smsYN = receiveI.getBooleanExtra("SMS", false);
		if (smsYN) {
			String msg = receiveI.getStringExtra("message");
			date = receiveI.getStringExtra("date");
			Log.d("date", date);
			String card = receiveI.getStringExtra("card");
			distributor = receiveI.getStringExtra("distributor"); // SMS수신내역 중 사용처 정보
			cost = receiveI.getStringExtra("cost");
			String phonenum = receiveI.getStringExtra("phonenum");
			addr = receiveI.getStringExtra("loginAddr");
			port = receiveI.getStringExtra("loginPort");
			doYN = true;

			ptdDpcDate_1 = "_".concat(date); // SMS 수신내용 중복처리 방지

		}
		return doYN;
	}

	private void initButtons(boolean doYN_tmp) {
		selection = doYN_tmp;

		btn_login = (Button) findViewById(R.id.btn_login_login);
		btn_login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				SharedPreferences prefs = getSharedPreferences("autoLogin", MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();

				// 자동로그인 기능 1
				String loginId = login_id.getText().toString();
				String loginPw = login_pw.getText().toString();
				String loginAddr = login_addr.getText().toString();
				String loginPort = login_port.getText().toString();

				if (loginId == null || loginId.equals("")) {
					new AlertDialog.Builder(MEIntro.this).setTitle("알림").setMessage("ID를 입력해 주세요").setPositiveButton("OK", null).show();
				} else if (loginPw == null || loginPw.equals("")) {
					new AlertDialog.Builder(MEIntro.this).setTitle("알림").setMessage("패스워드를 입력해 주세요").setPositiveButton("OK", null).show();
				} else {

					editor.putString("p_UserId", loginId); // 자동로그인 기능
					editor.putString("p_UserPw", loginPw);
					editor.putString("p_addr", loginAddr);
					editor.putString("p_port", loginPort);
					editor.commit();

					Toast.makeText(getApplicationContext(), "로그인 되었습니다.", Toast.LENGTH_LONG).show();

					if (selection) {// SMS 수신시

						if (!(ptdDpcDate_1.equals(ptdDpcDate_2))) { // SMS 수신내용 중복처리 방지
							ptdDpcDate_2 = "_".concat(date);

							Intent expRegI = new Intent(MEIntro.this, SocketClientService.class);
							expRegI.putExtra("id", 10);// 10 : login->expenseRegist
							expRegI.putExtra("loginId", loginId);
							expRegI.putExtra("loginPw", loginPw);
							expRegI.putExtra("loginAddr", loginAddr);
							expRegI.putExtra("loginPort", loginPort);
							expRegI.putExtra("date", date);
							expRegI.putExtra("cost", cost);
							expRegI.putExtra("distributor", distributor); // SMS수신내역 중 사용처 정보

							Log.d("SMS 수신시", "true");

							startService(expRegI);
						} else { // SMS 수신후, 재로그인할때 중복된 sms수신내역을 또 insert시키지 못하게 막음
							Intent loginI = new Intent(MEIntro.this, SocketClientService.class);
							loginI.putExtra("id", id);// 11
							loginI.putExtra("loginId", loginId);
							loginI.putExtra("loginPw", loginPw);
							loginI.putExtra("loginAddr", loginAddr);
							loginI.putExtra("loginPort", loginPort);
							Log.d("SMS 미수신시", "false");
							startService(loginI);
						}
					} else {// 로그인 시도, 처음부터 sms를 수신하지 않고 로그인하는 경우

						Intent loginI = new Intent(MEIntro.this, SocketClientService.class);
						loginI.putExtra("id", id);// 11
						loginI.putExtra("loginId", loginId);
						loginI.putExtra("loginPw", loginPw);
						loginI.putExtra("loginAddr", loginAddr);
						loginI.putExtra("loginPort", loginPort);
						Log.d("SMS 미수신시", "false");
						startService(loginI);
					}

				}
				// finish();
			}
		});

		btn_cancel = (Button) findViewById(R.id.btn_login_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				SharedPreferences prefs = getSharedPreferences("autoLogin", MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				editor.remove("p_UserId");
				editor.remove("p_UserPw");
				editor.remove("p_addr");
				editor.remove("p_port");
				editor.commit();
				Toast.makeText(getApplicationContext(), "로그인정보가 삭제되었습니다.", Toast.LENGTH_LONG).show();
				login_id.setText("");
				login_pw.setText("");
				login_addr.setText("");
				login_port.setText("");
			}
		});

	}

	private void redoLogin() {
		Intent receiveI = getIntent();
		boolean redoYN = receiveI.getBooleanExtra("restart", false);

		if (redoYN) {
			String selection = receiveI.getStringExtra("selection");
			if ("wrongId".equals(selection)) {
				new AlertDialog.Builder(MEIntro.this).setTitle("알림").setMessage("등록되지 않은 사용자입니다.").setPositiveButton("OK", null).show();
			} else if ("wrongPw".equals(selection)) {
				new AlertDialog.Builder(MEIntro.this).setTitle("알림").setMessage("패스워드가 일치하지 않습니다").setPositiveButton("OK", null).show();
			}
		}
	}
}
